package com.smm.web.mtower.util;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

/**
 * <p>
 * 协议解码器
 * </p>
 *
 * @author 曾世华
 * @version 1.0
 * @date 2016年1月21日
 */
public class ByteArrayDecoder extends CumulativeProtocolDecoder {

    private static final Logger logger = Logger.getLogger(ByteArrayDecoder.class);


    @Override
    public boolean doDecode(IoSession session, IoBuffer in,ProtocolDecoderOutput out) throws Exception {


        logger.info("接收到信息:"+in.toString());

        //in.prefixedDataAvailable(1, 19)
        int i = 1;
        String frist = "";
        String result = "";

        while (in.hasRemaining()) {

            byte data = in.get();

            if (frist.equals("")) {
                frist = Integer.toHexString(data & 0xff);
            }
            //以13开头，连续读取20字节
            if (frist.equals("13")) {

                if (i <= 20) {
                    result += Integer.toHexString(data & 0xff).length() == 1 ? "0" + Integer.toHexString(data & 0xff) : Integer.toHexString(data & 0xff);
                    if (i == 20) {
                        out.write(result);
                    }
                    i++;
                } else {
                    //重置。读取下一条消息
                    i = 1;
                    frist = "";
                    result = "";
                }
            }
            //System.out.println("i==="+i);
        }


        /**
         * 当这次读完毕
         */
        if (i < 20) {
            //System.out.println("返回false");
            return false;
        } else {
            //System.out.println("返回true");
            return true;
        }
    }

}
